package com.example.textsimilarity.service;

import com.baidu.aip.nlp.AipNlp;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;

@Service
public class TextSimilarityService {
    private static final Logger logger = LoggerFactory.getLogger(TextSimilarityService.class);
    
    private final AipNlp aipNlp;

    @Autowired
    public TextSimilarityService(AipNlp aipNlp) {
        this.aipNlp = aipNlp;
    }

    public double calculateSimilarity(String text1, String text2) {
        try {
            logger.info("Comparing texts - Text1: {}, Text2: {}", text1, text2);
            
            HashMap<String, Object> options = new HashMap<>();
            JSONObject response = aipNlp.simnet(text1, text2, options);
            
            logger.info("API Response: {}", response.toString());
            
            if (response.has("score")) {
                double score = response.getDouble("score");
                logger.info("Similarity score: {}", score);
                return score;
            } else if (response.has("error_code")) {
                logger.error("API Error: {}", response.toString());
                return 0.0;
            }
            
            logger.warn("Unexpected response format: {}", response.toString());
            return 0.0;
        } catch (Exception e) {
            logger.error("Error calculating similarity", e);
            return 0.0;
        }
    }
} 